<?php
namespace App\Models\Traits;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

trait LastActiveInfoHelper{
    protected $hash_table_prefix = 'bbschat_last_active_at_';
    protected $field_prefix = 'user_';
    public function recordLastActiveAt(){
        $date = Carbon::now()->toDateString();
        //bbschat_last_active_at_2024-07-05
        $hash_table_name = $this->hash_table_prefix.$date;
        //user_1
        $hash_field_name = $this->field_prefix.$this->id;
        //dd(Redis::hGetAll($hash_table_name));
        $now_time = Carbon::now()->toDateTimeString();
        Redis::hSet($hash_table_name,$hash_field_name,$now_time);
    }
    public function syncLastActivedAt(){
        $yesterday_date = Carbon::yesterday()->toDateString();
        //$yesterday_date = Carbon::now()->toDateString();
        $hash_table_name = $this->hash_table_prefix.$yesterday_date;
        $data = Redis::hGetAll($hash_table_name);
        foreach ($data as $user_id=>$actived_at){
            $user_arr =explode('_',$user_id);
            $user_id = $user_arr[1];
            if($user = $this->find($user_id)){
                $user->last_actived_at = $actived_at;
                $user->save();
            }
        }
        Redis::del($hash_table_name);
    }
    //访问器
    public function getLastActivedAtAttribute($value){
        $date = Carbon::now()->toDateString();
        //bbschat_last_active_at_2024-07-05
        $hash_table_name = $this->hash_table_prefix.$date;
        //user_1
        $hash_field_name = $this->field_prefix.$this->id;
        $datetime = Redis::hGet($hash_table_name,$hash_field_name) ?: $value;
        if($datetime){
            return new Carbon($datetime);
        }else{
            return $this->created_at;
        }
    }
}
